
import { http } from '@/utils/request';
import store from '@/store';
import api from "@/api/api"
import mHelper from '@/utils/helper';
/**
 * Promise封装wx.checkSession
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.qy.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * Promise封装wx.login
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.qy.login({
      success: function (res) {
        if (res.code) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {
  return new Promise(function (resolve, reject) {
    return login().then((res) => {
		http.post(api.registerWxLogin, { code: res.code }).then(r => {
			if(r.code =='0'){
				store.commit('login', r.result);	
			}else{
				mHelper.toast(r.message);
				setTimeout(() => { 
					uni.redirectTo({
					    url: '/pages/public/login'
					});
				}, 1000);
				
			}
		});
    })
  });
}

/**
 * 判断用户是否登录  
 */
async function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (uni.getStorageSync('userInfo') && uni.getStorageSync('accessToken')) {
		//后台查询token是否还有效.
		http.post(api.getUserMenuByToken, {}).then(r => {
			let code = r.code;
			if(code == "110"){
			   loginByWeixin();
			}
		});
        resolve(true);
    } else {
      reject(false);
    }
  });
}

module.exports = {
  loginByWeixin,
  checkLogin,
};